package edu.hubu.commons;

import edu.hubu.annotations.FilterField;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author moonlan
 * @date 2020/10/23 下午12:35
 */
public class Object2Map {

    private Object2Map() {

    }

    public static Map<String, Object> toMap(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        HashMap<String, Object> map = new HashMap<>();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(o);
                if (value != null && !value.toString().equals("")) {
                    map.put(field.getName(), value);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return map;
    }


    public static Map<String, Object> filterMap(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        HashMap<String, Object> map = new HashMap<>();
        for (Field field : fields) {
            field.setAccessible(true);
            if (!field.isAnnotationPresent(FilterField.class)) {
                try {
                    Object value = field.get(o);
                    if (value != null && !value.toString().equals("")) {
                        map.put(field.getName(), value);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
         return map;
    }
}
